<template>
<!-- // 粘贴图片墙 -->
<div>
  <div>
         <!-- <span><el-button
        v-on:click="uploadSelf()"
         >自动上传文件</el-button></span>

         <span><el-button
        v-on:click="uploadSelf()"
         >手动上传文件</el-button></span> -->

  <el-radio v-model="radio" label="1" border>自动上传</el-radio>
  <el-radio v-model="radio" label="2" border>手动上传</el-radio>
           <span><el-button 
        v-on:click="uploadPlans()"
         v-if="radio === '2'">上传</el-button></span>
         <div v-if="radio === '2'"><el-input
            placeholder="请输入图片名"
            v-model="inputName"
            clearable>
            </el-input>
          </div>

  </div>

<span>
<div class="box">
  <div id="preview" name="file" v-on:paste="handlePaste">
      <span style="color:#999">将图片按Ctrl+V 粘贴至此处</span>
      <!-- <span><img width="400px" height="400px" src="http://192.168.56.10:9000/youmans/2022-10-31/youmans_1667230613222.jpg"></span> -->
  </div>
  <!-- <el-button
        v-on:click="uploadPlans()"
         >上传文件</el-button> -->
</div>  
</span>

<ul>
<li>
  <div class="demo-image__lazy" >
    <el-image v-for="file in fileList" :key="file.uid" :src="file.url" class="cus-image">
       <div ref="imgDelete" class="delete-img">
                  <i class="el-icon-delete" @click="deleteImg()">删除</i>
                </div>
    </el-image>
    
  </div>
</li></ul>

</div>

</template>

<script>//importFile
import pictureApi from '@/api/dfs/picture'
import minioApi from '@/api/dfs/upload'
import { mapGetters } from 'vuex' //获取用户id
import moment from "moment"//时间戳
export default {
  name: 'picture_upload3',
    computed: {
    ...mapGetters([
      'avatar','name','userId'
    ])
  },
    data() {
    return {
      // list:[],
      page:1,
      limit:20,
      pictureQuery:{},
      titleName: '图片墙sir',
      form: {},
      dialogImageUrl: '',
      dialogVisible: true,
      fileList: [],
      picture:{},
      radio: '1',
      inputName:''
      // urls: [
      //     'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
      //     'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
      //     'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
      //     'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
      //     'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
      //     'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
      //     'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
      //   ]
    }
  },
  created () {
    //this.inited()
    this.getList2()
  },
  methods:{
    
    

    // inited(){
    //   preview.innerHTML = `<img width="400px" height="400px" src="http://192.168.56.10:9000/youmans/2022-10-31/youmans_1667230613222.jpg">`;
    // },

            //列表方法
        getList2(page = 1){
                // alert(this.userId)
          // const token = getToken();
            // alert(token)获取token

          // this.pictureQuery.username=`admin`
            this.page = page
            // console.log(this.pictureQuery)
            pictureApi.listByUserId(this.page,this.limit,this.pictureQuery)
            .then(response=>{//请求成功
            // response接口返回的数据
                // console.log(response)
                // this.list = response.data.records
                // this.total = response.data.total
                const imgList = response.data.records
                for (let i = 0; i < imgList.length; i++) {
                  // const userId = imgList[0].userId
                  this.fileList.push({
                    'uid': imgList[i].pid,
                    'url': imgList[i].newFilename
                  })
                }                

                 console.log(this.fileList)  
                //  console.log(this.total) ;
            })
            .catch(error =>{//请求失败
                console.log("请求失败:"+error)
            })
        }, 
        
        // =========================
                    // 上传成功回调 
    handleAvatarSuccess(res, file) {
      // console.log(res)
      if (res.code==20000) {
        console.log(res)
        // this.teacher.avatar = res.data
        // 强制重新渲染
        this.picture.newFilename=res.data
        this.picture.userId=this.userId
        console.log(this.picture)
        pictureApi.save(this.picture).then(response=>{
          // this.msgSuccess('上传成功')
          this.$message.success('上传成功')
        }).catch(error =>{//请求失败
                console.log("请求失败:"+error)
            })
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },

    // =======================================



     // 监听粘贴操作
    handlePaste(event) {
      const items = (event.clipboardData || window.clipboardData).items;
      let file = null;
// alert(file)
      if (!items || items.length === 0) {
        this.$message.error("当前浏览器不支持本地");
        return;
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
      if (!file) {
        this.$message.error("粘贴内容非图片");
        return;
      }
      // 此时file就是我们的剪切板中的图片对象
      // 如果需要预览，可以执行下面代码
      const reader = new FileReader();
      reader.onload = event => {
        preview.innerHTML = `<img src="${event.target.result}">`;
      };
      reader.readAsDataURL(file);
      this.file = file;
      if(this.radio === '1'){
             this.uploadPlans();//自动上传
      }
    },


    //上传文件成功后回调====================================
     uploadPlans() {
      let file = this.file;
      if (!file) {
        this.$message.error("请粘贴图片后上传");
        return;
      }
      

      this.loading = true;
      let form = new FormData();
      form.append("file", file);
      form.append("type", this.type);
    //uploadCertificate是封装的axios请求，自己根据需求传参
    // alert(form)
    //console.log(form)
      minioApi.upload_two(form)
        .then(data => {
          if (data.code==20000) {
            this.certificate_pic = data.data;
            

        // 强制重新渲染
        this.picture.pid=new Date().getTime()
        if(this.radio==='2'){
          if(!this.inputName){
            this.$message.error("请输入图片名！");
            return
          }
          this.picture.originalFilename=this.inputName+'.png'
        }else{
          this.picture.originalFilename='dfs截图'+moment().format('YYYYMMDDHHmmss')+'.png'
        }
        // this.picture.originalFilename='截图'+new Date()

        this.picture.newFilename=data.data
        this.picture.userId=this.userId
        console.log(this.picture)
        pictureApi.save(this.picture).then(response=>{
          // this.msgSuccess('上传成功')
          this.$message.success('上传成功')

          //this.$forceUpdate()
        }).catch(error =>{//请求失败
                console.log("请求失败:"+error)
            })
        //this.$forceUpdate()
          // this.getList2(1)
                  // this.fileList.push({
                  //   'uid': this.picture.pid,
                  //   'url': this.picture.originalFilename
                  // })
            this.fileList=[]
            preview.innerHTML =""
            this.file=''
            this.inputName=''
            this.getList2()

            // alert(this.certificate_pic)
            // this.$message.success("截图上传成功！");
            // this.$message.success(this.name + "上传成功！");

                  setTimeout(() => {
                    // preview.innerHTML = `<img width="400px" height="400px" src="http://192.168.56.10:9000/youmans/2022-10-31/youmans_1667230613222.jpg">`;          
              }, 1500)         
          } else {
            this.$message.error("截图上传失败！");
          }
        }).catch(() => {
            console.log("请求失败:"+error)
        });
    },

  }
}
</script>
<style lang="less">
    .box {
        width: 420px;
        height: 420px;
        resize: none;
        border: 1px solid #d2d2d2;
        border-radius: 4px;
      }
.personal {
  margin: 10px 0;
  padding: 10px;
  background: #f0f0f0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: hidden;
  border-radius: 3px;
  padding-bottom: 20px;
  .content {
    background-color: #fff;
    width: 100%;
    height: 100%;
    border-radius: 6px;
    padding: 10px;
    // overflow-y: scroll;
    overflow: hidden;
    display: flex;
    padding: 10px 0;
    flex-direction: column;
    //  1.标题及图像说明
    .content-desc {
      margin: 0px 10px;
      .title {
        font-size: 16px;
        border-left: 5px solid #2d8cf0;
        padding-left: 10px;
        margin-bottom: 16px;
      }
      .desc {
        margin-left: 18px;
      }
    }
    // 2.图像区域
    .content-image {
      margin: 25px 28px;
      .upload-photo {
        width: 580px;
        height: 200px;
        box-sizing: border-box;
        border-radius: 5px;
        cursor: pointer;
        margin-left: 20px;
        margin-top: 0px;
        padding-top: 0px;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        li {
          width: 180px;
          height: 180px;
          margin-right: 15px;
          position: relative;
          .delete-img {
            display: block;
            position: absolute;
            width: 180px;
            height: 40px;
            line-height: 40px;
            left: 0px;
            top: 140px;
            background: rgba(59, 60, 61, 0.5);
            // box-sizing: content-box;
            z-index: 999;
            cursor: pointer;
            text-align: right;
            i {
              margin: 8px 10px 0 0;
              display: block;
              font-size: 24px;
              color: white;
            }
          }
          img {
            border: 1px dashed #d9d9d9;
            border-radius: 5px;
            box-sizing: border-box;
            width: 180px;
            height: 180px;
            margin-top: 0px;
            &:hover {
              border: 1px dashed #409eff;
            }
          }
        }
      }
    }
  }
}
</style>